"""
工具10：知识库查询工具
功能：查询公司信息、FAQ等
"""
import json
import logging
from typing import Dict, Any
from langchain.tools import BaseTool
from pydantic import Field

logger = logging.getLogger(__name__)


class KnowledgeQueryTool(BaseTool):
    """知识库查询工具"""
    
    name: str = "knowledge_query_tool"
    description: str = """
        查询知识库（公司信息、FAQ等）。
        
        输入参数（JSON字符串）：
        {
            "query": "公司有哪些福利",
            "category": "company_info"  // 可选
        }
        """
    
    # 声明knowledge_base字段（Pydantic要求）
    knowledge_base: Dict[str, Any] = Field(default_factory=dict, exclude=True)
    
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        # 预设FAQ知识库
        kb = {
            "company_info": {
                "福利": "五险一金、年终奖、带薪年假、健康体检、团队建设、节日福利",
                "文化": "开放、创新、协作、成长",
                "办公": "弹性工作制、免费健身房、下午茶、休闲区"
            },
            "recruitment": {
                "流程": "简历筛选 → 初试 → 复试 → Offer → 入职",
                "周期": "一般2-3周",
                "面试": "1-2轮技术面试 + 1轮HR面试"
            }
        }
        object.__setattr__(self, 'knowledge_base', kb)
    
    def _run(self, query: str, category: str = "all") -> str:
        try:
            results = []
            
            # 搜索知识库
            if category == "all":
                search_dict = self.knowledge_base
            elif category in self.knowledge_base:
                search_dict = {category: self.knowledge_base[category]}
            else:
                search_dict = self.knowledge_base
            
            for cat, items in search_dict.items():
                for key, value in items.items():
                    if query in key or query in value:
                        results.append({
                            "category": cat,
                            "question": key,
                            "answer": value
                        })
            
            if not results:
                return json.dumps({
                    "success": True,
                    "data": [],
                    "message": "未找到相关信息，建议联系HR了解详情"
                }, ensure_ascii=False)
            
            return json.dumps({
                "success": True,
                "data": results,
                "message": f"找到{len(results)}条相关信息"
            }, ensure_ascii=False)
            
        except Exception as e:
            logger.error(f"知识库查询失败: {str(e)}")
            return json.dumps({
                "success": False,
                "error": str(e)
            }, ensure_ascii=False)
    
    async def _arun(self, *args, **kwargs):
        raise NotImplementedError()


